import {
  Form,
  Input,
  Modal,
  Button,
  Space,
  Select,
  Card,
  Spin,
  message,
} from "antd";
import { useEffect, useState } from "react";
import { namespace } from "../configFile";
import { connect, useParams, history } from "umi";
import styles from "../styles.less";
import Https from "@/utils/Https";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import TextArea from "antd/es/input/TextArea";

const SettingPanel = (props) => {
  const { dispatch, prev, info, isFooter } = props;
  const [open, setOpen] = useState(false); //编辑弹窗
  const [editItem, setEditItem] = useState({}); //编辑的条目
  const [form2] = Form.useForm();
  const [settingForm] = Form.useForm();
  const params = useParams();
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([
    {
      key: 0,
      contentTtem: "特色",
      expound: "",
      sort: "1",
      status: 0,
    },
    {
      key: 1,
      contentTtem: "要求",
      expound: "",
      sort: "2",
      status: 0,
    },
    {
      key: 2,
      contentTtem: "材料",
      expound: "",
      sort: "3",
      status: 0,
    },
  ]);
  const columns = [
    {
      title: "内容项",
      dataIndex: "contentTtem",
      align: "center",
      width: 150,
      editable: false,
    },
    {
      title: "详细说明",
      dataIndex: "expound",
      align: "left",
      width: 800,
      renderFormItem: (_, { isEditable }) => {
        return (
          isEditable && (
            <TextArea
              placeholder="请输入详细说明"
              maxLength={500}
              allowClear
              showCount
              style={{ height: 120, resize: "none" }}
            />
          )
        );
      },
      render: (_, row) => row.expound,
    },
    {
      title: "操作",
      fixed: "right",
      dataIndex: "operate",
      width: 150,
      align: "center",
      valueType: "option",
      render: (text, record, index, action) => (
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>
      ),
    },
  ];
  useEffect(() => {
    dispatch({
      type: `${namespace}/getCourseTemplateList`,
    });
  }, []);

  const updateInstr = async () => {
    const request = await form2.validateFields();
    dataSource.map((item) => {
      if (item.key === editItem.key) {
        item.expound = request.expound;
        item.sort = request.sort;
      }
    });
    setDataSource([...dataSource]);
    setEditItem({});
    setOpen(false);
    form2.resetFields();
  };
  const submit = async () => {
    settingForm.validateFields().then(async (request) => {
      if (request.appointFlow) {
        let hasFlow = props.courseTemplateList.some(function (o) {
          return o.id == request.appointFlow;
        });
        if (!hasFlow) {
          message.error(
            "当前约课流程不存在，请重新选择或在‘系统设置-约课模版’中新增"
          );
          return;
        }
      }
      request.classInstructions = JSON.stringify(dataSource);
      request.appointFlow = request.appointFlow ? request.appointFlow : "";
      request.appointRule = 0;
      if (params.num) {
        let obj = {
          id: params.id,
          ...request,
          venueId: info.venueId,
        };
        let res: any = await Https.post("/course/updateCourseInfo", obj, true);
        setLoading(true);
        if (res.code === 200) {
          message.success("保存成功");
          history.push("/course/info", { courseType: params.courseType });
        } else {
          message.error(res.msg);
        }
        setLoading(false);
      } else {
        props.submit(1, request);
      }
    });
  };
  useEffect(() => {
    if (Object.keys(info).length > 0) {
      const { appointRule, classInstructions, appointFlow } = info;
      if (classInstructions) {
        setDataSource(JSON.parse(classInstructions));
      }
      settingForm.setFieldsValue({
        appointRule: Number(appointRule),
        appointFlow: appointFlow,
      });
    }
  }, [info]);
  return (
    <Spin spinning={loading}>
      <PageContainer
        footer={[
          isFooter ? (
            <div className={styles.formBtn}>
              {params.num ? (
                <Button type="primary" size="large" onClick={() => submit()}>
                  保存
                </Button>
              ) : (
                <>
                  <Button size="large" onClick={() => prev()}>
                    上一步
                  </Button>
                  <Button
                    type="primary"
                    size="large"
                    style={{ marginLeft: "20px" }}
                    onClick={() => submit()}
                  >
                    下一步
                  </Button>
                </>
              )}
            </div>
          ) : null,
        ]}
      >
        <Form
          form={settingForm}
          className={styles.setForm}
          initialValues={{
            appointRule: 0,
          }}
        >
          <Card
            title="上课说明设置"
            style={{ width: "100%", marginBottom: "16px" }}
          >
            <Form.Item name="classInstructions" style={{ width: "100%" }}>
              <ProTable
                bordered
                rowKey="key"
                pagination={false}
                columns={columns}
                dataSource={dataSource}
                options={false}
                search={false}
                editable={{
                  onSave: async (index, record) => {
                    let objList = [...dataSource];
                    objList[index].expound = record.expound;
                    setDataSource([...objList]);
                  },
                  actionRender: (row, config, defaultDom) => [
                    defaultDom.save,
                    defaultDom.cancel,
                  ],
                }}
              />
            </Form.Item>
          </Card>
          <Card title="其他设置" style={{ width: "100%" }}>
            <Form.Item
              label="约课流程"
              name="appointFlow"
              extra="可以在系统设置-约课流程中设置"
              style={{ width: "40%" }}
            >
              <Select
                allowClear
                style={{ width: "100%" }}
                placeholder="请选择约课流程"
                options={props.courseTemplateList}
                fieldNames={{
                  label: "templateName",
                  value: "id",
                }}
              />
            </Form.Item>
          </Card>
          <Modal
            forceRender
            title="上课说明编辑"
            width={800}
            destroyOnClose={true}
            open={open}
            onCancel={() => setOpen(!open)}
            footer={
              <Space>
                <Button onClick={() => setOpen(false)}>取消</Button>
                <Button onClick={() => updateInstr()} type="primary">
                  确定
                </Button>
              </Space>
            }
          >
            <Form form={form2} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }}>
              <Form.Item label="内容项">{editItem.contentTtem}</Form.Item>
              <Form.Item label="详细说明" name="expound">
                <Input />
              </Form.Item>
              <Form.Item label="排序值" name="sort">
                <Input />
              </Form.Item>
            </Form>
          </Modal>
        </Form>
      </PageContainer>
    </Spin>
  );
};

export default connect((state) => {
  return {
    ...state[namespace],
    submitLoading: state.loading.effects[`${namespace}/submitItem`],
  };
})(SettingPanel);
